#include <aos/aos.h>
#include "aos/cli.h"
#include <stdio.h>
#include <pthread.h>
#include <debug/dbg.h>

#define ANV_LEAKS_IMPLEMENTATION
#include <anv_leaks.h>

static void * anv_memleak_thread(void *arg)
{
    anv_leak_info **leaks;
    size_t leaks_count;

    anv_leaks_init(stdout);

    void *mem = malloc(10);
    anv_leaks_quickpeek();

    free(mem);
    anv_leaks_quickpeek();

    anv_leaks_stats stats;
    anv_leaks_get_stats(&stats);

    aos_debug_printf("[total] %d allocated, %d freed\n", stats.total_allocated, stats.total_freed);
    aos_debug_printf("[count] %d malloc, %d free\n", stats.malloc_count, stats.free_count);
    aos_debug_printf("[count] %d calloc, %d realloc\n", stats.calloc_count, stats.realloc_count);

    anv_leaks_get_leaks(&leaks, &leaks_count);

    aos_debug_printf("\n");
    aos_debug_printf("[total] %d leaks\n", leaks_count);

    for (int i = 0; i < leaks_count; ++i)
    {
        aos_debug_printf("[%s] line %d, %d bytes\n", leaks[i]->filename,  leaks[i]->line, leaks[i]->bytes);
    }
    anv_leaks_free_info(leaks, leaks_count);

    return 0;
}

int yoc_anv_memleak_example(int argc, char *argv[])
{
    int ret = 0;
    int thread_para;
    pthread_t new_thread;
    pthread_attr_t attr;
    int *retval;

    thread_para = 10;
    pthread_attr_init(&attr);
    pthread_attr_setstacksize(&attr, 4096);
    ret = pthread_create(&new_thread, &attr, anv_memleak_thread, &thread_para);
    if (ret != 0) {
        printf("pthread_create failed, ret:%d\n", ret);
        pthread_attr_destroy(&attr);
        return -1;
    }
    return 0;
}
ALIOS_CLI_CMD_REGISTER(yoc_anv_memleak_example, yoc_anv_memleak_example ,anv memleak example);
